<template>
  <div class="content-table">
    <el-card>
      <!-- class="project-list-container" -->
      <div>
        <div class="list-h">
          <el-button
            type="primary"
            @click="handleOpen"
            class="add-option"
            v-auth="`/system/manage--add`"
            >添加人员</el-button
          >
          <el-form
            :inline="true"
            class="demo-form-inline"
            :model="formInline"
            ref="formRef"
            @submit.prevent
          >
            <el-form-item label="用户名" prop="userNameLike">
              <el-input
                v-model.trim="formInline.userNameLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="nameLike">
              <el-input
                v-model.trim="formInline.nameLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item label="单位" prop="companyNameLike">
              <el-input
                v-model.trim="formInline.companyNameLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <!-- <el-form-item label="职称" prop="positionalTitlesLike">
              <el-input
                v-model.trim="formInline.positionalTitlesLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item label="类型" prop="kcMemberCode">
              <el-select
                v-model="formInline.kcMemberCode"
                filterable
                clearable
                class="width-custom120"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in userTypeList"
                  :label="item.dicValue"
                  :key="item.dicCode"
                  :value="item.dicCode"
                >
                </el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item label="角色" prop="rolesList">
              <el-select
                v-model="formInline.rolesList"
                filterable
                clearable
                class="width-custom120"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in userRoleList"
                  :label="item.roleName"
                  :key="item.id"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="handleReset">重置</el-button>
              <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-skeleton style="height: 50vh" :rows="8" :loading="loading" animated>
          <el-table
            :data="state.tableData"
            border
            v-loading="loading"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          >
            <template #empty>
              <el-empty :image-size="150" description="暂无数据"></el-empty>
            </template>
            <!-- <el-table-column prop="id" label="ID" width="50"></el-table-column> -->
            <el-table-column type="index" label="序号" width="60">
              <template v-slot="scope">
                <span>{{
                  (formInline.pageNum - 1) * formInline.pageSize +
                  scope.$index +
                  1
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="userName" label="用户名"></el-table-column>
            <el-table-column
              prop="name"
              label="姓名"
              width="110"
            ></el-table-column>
            <!-- <el-table-column prop="nickName" label="昵称"></el-table-column> -->
            <!-- <el-table-column prop="email" label="邮箱"></el-table-column> -->
            <!-- <el-table-column prop="address" label="地址"></el-table-column> -->
            <!-- <el-table-column prop="age" label="年龄"></el-table-column> -->
            <el-table-column label="单位" min-width="120">
              <template #default="{ row }">
                {{ row.isEmp === "1" ? row.memo : row.companyName }}
              </template>
            </el-table-column>
            <!-- <el-table-column prop="deviceId" label="设备ID"></el-table-column> -->

            <!-- <el-table-column prop="phoneNum" label="手机号"></el-table-column> -->
            <!-- <el-table-column prop="photo" label="头像"></el-table-column> -->

            <el-table-column prop="roleName" label="角色"></el-table-column>

            <!-- <el-table-column prop="remark" label="备注"></el-table-column> -->

            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定重置该条密码吗？"
                  @confirm="handleResetPassword(row)"
                >
                  <template #reference>
                    <el-button type="text">重置密码</el-button>
                  </template>
                </el-popconfirm>
                <el-button type="text" @click="handleEdit(row)">编辑</el-button>
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定删除该条记录吗？"
                  @confirm="handleDelete(row)"
                >
                  <template #reference>
                    <el-button :disabled="row.isEmp === '1'" type="text"
                      >删除</el-button
                    >
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-skeleton>
      </div>
      <re-pagination
        :total="total"
        v-show="total > 0"
        v-model:page="formInline.pageNum"
        v-model:limit="formInline.pageSize"
        @pagination="handleSearch"
      />
    </el-card>
    <el-dialog
      :title="mode === 'add' ? '添加人员' : '编辑人员'"
      v-model="dialogFormVisible"
      destroy-on-close
      width="600px"
    >
      <user-detail
        @emitClose="emitClose"
        :mode="mode"
        :userInfo="state.userInfo"
        :companyInfo="state.companyInfo"
      />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import UserDetail from "./components/UserDetail.vue";

import NotifMessage from "/@/utils/message/notification";
import { getUserSysList, deleteUser, resetPassword } from "/@/api/user";
import { ModeType, UserInfoType } from "./types";
import { postDictList } from "/@/api/common";
import { roleList } from "/@/api/roles";

const formRef = ref<HTMLFormElement | null>(null) as any;

let loading = ref<boolean>(false);
let mode = ref<ModeType>("add");
let dialogFormVisible = ref<boolean>(false);
let total = ref<number>(0);
let formInline = reactive<any>({
  nameLike: "",
  userNameLike: "",
  companyNameLike: "",
  positionalTitlesLike: "",
  kcMemberCode: "",
  userRolesList: "",
  pageNum: 1,
  pageSize: 10
});

let state = reactive({
  tableData: [] as UserInfoType[],
  userInfo: {} as UserInfoType,
  companyInfo: {}
});

let userTypeList = ref([]);

let userRoleList = ref([]);

// 请求表格数据
async function getTableData(obj: object = {}) {
  // 真实请求待添加
  loading.value = true;
  try {
    const { code, data } = await getUserSysList(obj);
    if (code === 200) {
      state.tableData = data.list;
      total.value = data.rows;
    }
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
}
// 打开添加人员弹窗
const handleOpen = (): void => {
  dialogFormVisible.value = true;
  mode.value = "add";
  // console.log(activeCategory);
  // if (activeCategory.value.id) {
  // state.companyInfo = activeCategory;
  // }
};

const emitClose = (isSubmit: boolean) => {
  dialogFormVisible.value = false;
  if (isSubmit) {
    formInline.pageNum = 1;
    getTableData(formInline);
  }
};

// 重置条件
const handleReset = (): void => {
  formRef.value.resetFields();
};

// 根据条件进行搜索
const handleSearch = (): void => {
  const copy = JSON.parse(JSON.stringify(formInline));
  copy.rolesList = formInline.rolesList ? [formInline.rolesList] : [];
  getTableData(copy);
};

// 编辑用户
const handleEdit = (row): void => {
  dialogFormVisible.value = true;
  mode.value = "edit";
  state.userInfo = row;
};

// 删除用户
const handleDelete = async (item: any) => {
  try {
    const { code, message } = await deleteUser({ id: item.id });
    if (code === 200) {
      // successMessage(`${message}`);
      NotifMessage.success(message);
      getTableData(formInline);
    } else {
      // warnMessage(`${message}`);
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

// 重置密码
const handleResetPassword = async (item: any) => {
  try {
    const { code, message } = await resetPassword({ id: item.id });
    if (code === 200) {
      NotifMessage.success(message);
      getTableData(formInline);
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

// 人员类型
const initUserTypeList = async () => {
  try {
    const params = {
      dicType: "rd_user_type"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      userTypeList.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

// 人员角色
const initUserRoleList = async () => {
  try {
    const params = {
      pageNum: 1,
      pageSize: 0
    };
    const { code, data } = await roleList(params);
    if (code === 200) {
      userRoleList.value = data.list;
    }
  } catch (err) {
    console.log(err);
  }
};

// 请求数据
getTableData(formInline);
initUserTypeList();
initUserRoleList();
</script>

<style lang="scss" scoped></style>
